﻿using AutoUpdater.Bll;
using AutoUpdater.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoUpdater
{
    public class CsUpdater
    {
        private string _basePath;
        public event Action<string> UpdateCompleted;
        public event Action ConnectionInterrupted;

        private Thread thread;

        public CsUpdater(string basePath)
        {
            _basePath = basePath;
        }

        public void Start()
        {
            if(thread != null)
            {
                try
                {
                    thread.Abort();
                }
                catch (Exception ex) { }
            }

            thread = new Thread(DealUpdate);
            thread.Start();
        }

        private void DealUpdate()
        {
            //1. 获取本地程序版本号
            string clientVersion = VersionXmlUtil.GetBaseFileVersion();
            string baseFileVersion = VersionXmlUtil.GetUpdateExeVersion();
            string projectFileVersion = VersionXmlUtil.GetUpdateExeVersion();

            FileCheckReq fileCheckReq = new FileCheckReq();
            fileCheckReq.clientVersion = VersionXmlUtil.GetClientVersion();
            fileCheckReq.FileVersion = VersionXmlUtil.GetProjectFileVersion();
            fileCheckReq.baseFileVersion = VersionXmlUtil.GetBaseFileVersion();

            var contract = FileCheckBll.CheckUpdateExeFile(fileCheckReq);

            if(contract == null)
            {
                UpdateCompleted(null);
                return;
            }

            UpdateFileUtil updateFileUtil = new UpdateFileUtil(contract);
            string error = updateFileUtil.downLoadFile();

            VersionXmlUtil.SetUpdateExeCurrentUpdateVersion(contract.clientVersion);
            UpdateCompleted(null);
        }
    }
}
